//
//  CustomKeyboard.m
//  测试
//
//  Created by 李李善 on 2017/4/19.
//  Copyright © 2017年 森之源. All rights reserved.
//

#import "CustomInputBoard.h"
#import <Masonry/Masonry.h>

@interface CustomInputBoard()

@end
@implementation CustomInputBoard
@synthesize mDelegate;
#pragma mark- 移除通知
-(void)dealloc
{
     NSLog(@"%@ 这个类被强暴了",NSStringFromClass([self class]));
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

+(CustomInputBoard *)customKeyboard
{
//    static CustomInputBoard * customKeyboard = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
          CustomInputBoard * customKeyboard = [[CustomInputBoard alloc] init];
//    });
    return customKeyboard;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.backgroundColor =[UIColor whiteColor];
        //初始化的时候设为NO
        self.isTop = NO;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}


-(void)textViewShowView:(UIViewController *)viewController type:(crearchType)type customKeyboardDelegate:(id)delegate
{
    
    [viewController.view addSubview:self];
    
    self.mViewController =viewController;
    self.mDelegate =delegate;
    
    self.type = type;
    
    if (type==crearchTypeKongJian) {
       [self setFrame:CGRectMake(0,kScreenH, kScreenW,kFitH(50))];
    }else
    {
//        NSLog(@"%d---%d",kScreenH,kScreenW);
       [self setFrame:CGRectMake(0,kScreenH-kFitH(110),kScreenW,kFitH(50))];
    }
     self.mSecondaryBackView= ({
        UIView *l =[[UIView alloc]init];
         l.backgroundColor = [UIColor whiteColor];
          [self addSubview:l];
        l;
    });
    WSELF(weakSelf);
    [self.mSecondaryBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(kFitW(10)));
        make.right.equalTo(weakSelf.mas_right).offset(-kFitW(80));
        make.top.equalTo(weakSelf.mas_top).offset(5);
        make.bottom.equalTo(weakSelf.mas_bottom).offset(-5);
    }];
    
    self.mTextView = ({
        HLTextView*l=[[HLTextView alloc]init];
        l.backgroundColor =[UIColor whiteColor];
        l.placeholder = @"评论";
        [l setTextColor:[UIColor lightGrayColor]];
        l.borderWidth = 0;
        l.font = kSysFont(kFitW(13));
        l.borderColor = [UIColor colorWithHexString:@"0xb6b6b6"];
        l.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;;
        l.delegate = self;
        [self.mSecondaryBackView addSubview:l];
        l;
    });
    
    
    [self.mTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.mSecondaryBackView).with.insets(UIEdgeInsetsMake(0.5f, 0.5f, 0.5f, 0.5f));
    }];
    
    self.mTalkBtn = ({
        UIButton*l=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [l setTitle:@"发送" forState:UIControlStateNormal];
        [l addTarget:self action:@selector(forTalk) forControlEvents:UIControlEventTouchUpInside];
        [l setBackgroundColor:[UIColor lightGrayColor]];
        [l setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [l setEnabled:NO];
        [l setTintColor:[UIColor blackColor]];
        [self addSubview:l];
        l;
    });
    
    [self.mTalkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mTextView.mas_right).offset(kFitW(10));
        make.height.equalTo(@(kFitH(39)));
        make.bottom.equalTo(weakSelf.mTextView);
        make.right.equalTo(weakSelf.mas_right).offset(-kFitW(10));
    }];
    
 
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.mTextView resignFirstResponder];
    return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.mTextView.text = nil;
    return YES;
}

//评论按钮
-(void)forTalk
{
    
    if (self.isTop ==NO)
    {
        [self.mTextView becomeFirstResponder];
    }
    else
    {
        [mDelegate talkBtnClick:self.mTextView];
        
        if (self.mTextView.text.length==0)
        {
            NSLog(@"内容为空");
        }
        else
        {
            [self.mTextView resignFirstResponder];
        }
    }
    
    self.mTextView.text = @"";
    
}
#pragma mark- 点击屏幕其他地方 键盘消失
-(void)hideView
{
    NSLog(@"屏幕消失");
    [self.mTextView resignFirstResponder];
}

#pragma mark- 键盘出现
- (void)keyboardWillShow:(NSNotification*)notification
{

    self.isTop =YES;
    // 获取通知的信息字典
    NSDictionary *userInfo = [notification userInfo];
    
    // 获取键盘弹出后的rect
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect _keyboardRect = [aValue CGRectValue];
    
    
    // 获取键盘弹出动画时间
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    NSLog(@"%f-%f",_keyboardRect.origin.y,_keyboardRect.size.height);
    
    if (!self.mHiddeView)
    {
        self.mHiddeView = ({
            UIView *l =[[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenW,kScreenH)];
            l.backgroundColor =[UIColor blackColor];
            l.alpha =0.0f;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideView)];
            self.userInteractionEnabled = YES;
            [l addGestureRecognizer:tap];
            [self.mViewController.view addSubview:l];
            l;
        });
        
    }
    WSELF(weakSelf);//
    [UIView animateWithDuration:animationDuration animations:^{
        weakSelf.mHiddeView.alpha =0.4f;//_keyboardRect.size.height-kFitH(55)
        weakSelf.frame =CGRectMake(0,kScreenH-_keyboardRect.size.height-kFitH(50)-64, kScreenW, kFitH(50));
    } completion:^(BOOL finished) {
        [weakSelf.mViewController.view bringSubviewToFront:weakSelf];
    }];
}


#pragma mark- 键盘下落
- (void)keyboardWillHide:(NSNotification*)notification
{
    self.isTop =NO;
    
    
    // 获取通知的信息字典
    NSDictionary *userInfo = [notification userInfo];
    
    
    // 获取键盘弹出动画时间
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    WSELF(weakSelf);
    [UIView animateWithDuration:animationDuration animations:^{
        
        if (weakSelf.type==crearchTypeKongJian) {
            weakSelf.frame=CGRectMake(0,kScreenH-kFitH(50+64), kScreenW,kFitH(50));
        }else
        {
            [weakSelf setFrame:CGRectMake(0,kScreenH-kFitH(110), kScreenW,kFitH(50))];
        }
        weakSelf.mHiddeView.alpha =0.0f;
        [weakSelf.mTalkBtn setBackgroundColor:[UIColor lightGrayColor]];
        [weakSelf.mTalkBtn setEnabled:NO];
    } completion:^(BOOL finished) {
        [weakSelf.mHiddeView removeFromSuperview];
        weakSelf.mHiddeView =nil;
        [weakSelf.mTextView setTextColor:[UIColor lightGrayColor]];

    }];
    
    if ([self.mDelegate respondsToSelector:@selector(keyboardDown:)]) {
        [self.mDelegate keyboardDown:self];
    }
}


#pragma mark- 监听文字改变 换行时要更改输入框的位置
- (void)textDidChanged:(NSNotification *)notif
{
    CGSize contentSize = self.mTextView.contentSize;
    
    if (contentSize.height >= 141){
        return;
    }
    CGFloat minus = 3;
    CGRect selfFrame = self.frame;
    CGFloat selfHeight = self.mTextView.superview.frame.origin.y * 2 + contentSize.height - minus + 2 * 2;
    CGFloat selfOriginY = selfFrame.origin.y - (selfHeight - selfFrame.size.height);
    selfFrame.origin.y = selfOriginY;
    selfFrame.size.height = selfHeight;
    NSString *text =self.mTextView.text;
    UIColor *color =text.length!=0? [UIColor blueColor]:[UIColor lightGrayColor];
    [self.mTalkBtn setEnabled:text.length!=0?YES:NO];
    [self.mTalkBtn setBackgroundColor:color];
    [self.mTextView setTextColor:[UIColor blackColor]];
    if ((selfFrame.size.height >= kFitH(50))) {
        self.frame = selfFrame;
    }
    NSLog(@"文字改变");
}


/*
 *  开启评论键盘
 */
- (void)keyboardUpforComment
{
   
    
    if (_isTop == YES) {
        return;
    }
    [self.mTextView becomeFirstResponder];
//    _isTop = !_isTop;
}

/**
 *  隐藏评论键盘
 */
- (void)keyboardDownForComment
{
 
    if (_isTop == NO) {
        return;
    }
   
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        
//        self.lastChatKeyboardY = self.frame.origin.y;
//
//        [self.chatToolBar prepareForEndComment];
//        self.frame = CGRectMake(0, [self getSuperViewH], self.frame.size.width, CGRectGetHeight(self.frame));
//
//        [self updateAssociateTableViewFrame];
        
    } completion:nil];
//    _isTop = !_isTop;
}


@end
